package com.ouroboroswiki.core.content;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ouroboroswiki.core.AbstractContentRepository;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.MultipartVersion;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class SkipPathStepContentRepositoryProxy extends AbstractContentRepository {
	
	private ContentRepository proxied;
	
	public SkipPathStepContentRepositoryProxy( ) {
	}
	
	public void setProxied( ContentRepository proxied ) {
		this.proxied = proxied;
	}

	@Override
	public boolean exists(Object principal, ContentPath path) throws ContentException {
		boolean exists = false;
		List<ContentPath> children = path.getChildren();
		for( int i=0; i<children.size() && !exists; i++ ) {
			exists = proxied.exists(principal, children.get( i ));
		}
		return exists;
	}

	@Override
	public Content getContent(Object principal, ContentPath path, Version version, Map<String, Object> properties)
			throws ContentException {
		List<ContentPath> children = path.getChildren();
		HashMap<String, Content> childContents = new HashMap<String, Content>(children.size());
		boolean exists = false;
		boolean writable = children.size() == 1;
		String mimeType = null;
		for( int i=0; i<children.size(); i++ ) {
			ContentPath childPath = children.get( i );
			Content childContent = proxied.getContent(principal, childPath, version, properties);
			exists = exists || childContent.exists();
			writable = writable && childContent.isWritable();
			mimeType = childContent.getMimeType();
			String name;
			if( i == 0 ) {
				name = Content.CHILD_CONTENT_MAIN;
			} else {
				name = Content.CHILD_CONTENT_MAIN + '_' + i;
			}
			childContents.put( name, childContent );
		}
		CompositeContent result = new CompositeContent(childContents);
		result.setExists(exists);
		result.setWritable(writable);
		result.setMimeType( mimeType );
		result.setUniqueName(path.toString());
		result.setRepositoryName(getName());
		return result;
	}

	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		List<ContentPath> children = path.getChildren();
		HashMap<String, Version> childVersions = new HashMap<String, Version>(children.size());
		for( int i=0; i<children.size(); i++ ) {
			ContentPath childPath = children.get( i );
			Version childVersion = proxied.buildVersion(principal, childPath, versionPath, versionBuilder);
			childVersions.put( Integer.toString( i ), childVersion );
		}
		return new MultipartVersion(childVersions);
	}
}
